package com.open.pay.wechat.infrastructure.config;

import com.open.framework.exception.BusinessException;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhang kaichao
 * @since 2021/2/24 14:00:13
 */
@AllArgsConstructor
@Configuration
public class WxPayConfiguration {

    private final WxPayConfig wxPayConfig;

    @Bean
    public WxPayService wxPayService() {
        final List<WxPayProperties> configs = wxPayConfig.getConfigs();
        if (configs == null) {
            throw new BusinessException("未添加支付配置信息");
        }
        WxPayService service = new WxPayService();
        service.setMultiConfigStorages(configs
                .stream().map(a -> {
                    WxPayConfigStorageImpl configStorage = new WxPayConfigStorageImpl();
                    configStorage.setAppID(a.getAppId());
                    configStorage.setNotifyUrl(a.getNotifyUrl());
                    configStorage.setMchID(a.getMchId());
                    configStorage.setKey(a.getKey());
                    configStorage.setSignType(a.getSignType());
                    configStorage.setHttpConnectTimeoutMs(a.getHttpConnectTimeoutMs());
                    configStorage.setHttpReadTimeoutMs(a.getHttpReadTimeoutMs());
                    configStorage.setUseSandbox(a.getUseSandbox());
                    configStorage.setCertName(a.getCertName());
                    configStorage.setCertData();
                    return configStorage;
                }).collect(Collectors.toMap(WxPayConfigStorageImpl::getAppID, a -> a, (o, n) -> o)));
        return service;
    }

}
